var Admin = require('../model/admin.js');

/**
 * login, check loginId-password match or not
 * @param loginId
 * @param password
 * @return promise
 */
function isMatch(loginId, password) {
    return Admin.find()
        .select('_id')
        .limit(1)
        .and([{password: password},
            {$or: [{name: loginId}, {email: loginId}]}
        ])
        .exec()
        .then(function ok(doc) {
            if (doc.length !== 0) {
                return Promise.resolve({
                    errcode: 200,
                    errmsg: 'matched'
                });
            } else {
                return Promise.reject({
                    errcode: 401,
                    errmsg: 'wrong id or password'
                });
            }

        }, function error(err) {
            return Promise.reject({
                errcode: 500,
                errmsg: 'wrong on db' + err
            });
        });
}

function fetchAll() {
    return Admin.find().exec();
}

function findOne(cond) {
    return Admin.findOne(cond).exec();
}

function findById(id) {
    return Admin.findOne({_id: id}).exec();
}

var dao = {
    isMatch: isMatch,
    fetchAll: fetchAll,
    findOne: findOne,
    findById: findById
};

exports = module.exports = dao;